import matplotlib.pyplot as plt
import numpy as np
import os

def get_a_file_data(filename, need_key):
    with open(filename, 'r') as f:
        row_list = f.read().splitlines()
    
    for row in row_list:
        key, value = row.split(':')
        if key == need_key:
            return eval(value)

    
def plot_miss_count(y1,y2):
    x_data_old = ['MID', 'EDF', 'SEDF', 'SRPT', 'FB', 'THR', 'OPTFB', 'RM', 'SRPT+EDF', 'SRPT-A', 'FIFO', 'FIFO+EDF']
    
    y_data1_old = y1
    y_data2_old = y2

    data_dict = {}
    for i in range(len(x_data_old)):
        data_dict[x_data_old[i]] = y_data1_old[i]
    x_data = ['FIFO','FIFO+EDF','RM','SRPT-A','SRPT','EDF','SEDF','SRPT+EDF','FB']
    y_data1 = [data_dict[label] for label in x_data]
    ind = np.arange(len(x_data))
    w = 0.2
    plt.figure(figsize=(5, 4.7))
    ax = plt.subplot(111)
    a = ax.bar(ind,y_data1,width=0.2,align='center')

    data_dict = {}
    for i in range(len(x_data_old)):
        data_dict[x_data_old[i]] = y_data2_old[i]
    x_data = ['FIFO','FIFO+EDF','RM','SRPT-A','SRPT','EDF','SEDF','SRPT+EDF','FB']
    y_data2 = [data_dict[label] for label in x_data]
    b = ax.bar(ind+w,y_data2,width=0.2,align='center')
    ax.set_xticks(ind+w)
    ax.set_xticklabels( ('FIFO','FIFO+EDF','RM','SRPT-A','SRPT','EDF','SEDF','SRPT+EDF','FB') )
    plt.legend((a,b),('AveMissCount','WorstMissCount'), fontsize=18)
    plt.autoscale(tight=True)
    plt.yticks(fontsize=22)
    plt.xticks(fontsize=22,  rotation = 280)
    # plt.title('The average/worst number of jobs that missed their deadlines', fontsize=22)
    plt.tight_layout()
    graph_path = os.path.dirname(os.path.abspath(__file__)) + '/graph/'
    if not os.path.isdir(graph_path):
        os.makedirs(graph_path)
    file_name = graph_path + __file__.split('/')[-1].split('.')[0]
    plt.savefig(f"{file_name}.pdf", bbox_inches='tight')
    plt.close()
        

if __name__ == "__main__":
    total_data = []
    for i in range(10):
        res = get_a_file_data(f'../../8_9_9_synchronous/test{i}/result_data.log', 'average miss ddl')
        total_data.append(res)
        np_total_data = np.array(total_data)
        print(res)
    y1 = np_total_data.mean(axis = 0).tolist()
    print("mean miss:",y1)
    total_data = []
    for i in range(10):
        res = get_a_file_data(f'../../8_9_9_synchronous/test{i}/result_data.log', 'worst miss ddl')
        total_data.append(res)
        np_total_data = np.array(total_data)
        print(res)
    y2 = np_total_data.max(axis = 0).tolist()
    print("['MID', 'EDF', 'INS', 'SRPT', 'FB', 'THR', 'OPTFB', 'RM', 'SEDF', 'SALL', 'FIFO', 'FEDF']")
    print("miss count", y2)
    plot_miss_count(y1,y2)

        


